﻿// E-Book Copier
// Copyright (C) 2009 Chuan-Gen Fan
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
// 
// Project: http://code.google.com/p/ebookcopier/
// Contact Author:
//    website: http://chuangen.name/
// e-mail/msn: chuangen@live.cn

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.IO;
using EbookCopier.Ref;

namespace EbookCopier
{
    /// <summary>
    /// 主窗体。
    /// </summary>
    public partial class MainForm : Form
    {
        /// <summary>
        /// 文档标题
        /// </summary>
        string docTitle = "";

        Properties.Settings settings = Properties.Settings.Default;
        CaptureHelper captureHelper = null;
        PdfCreator pdfCreator = null;

        string caption = "";
        /// <summary>
        /// 初始化类 <see cref="MainForm"/> 的新实例。
        /// </summary>
        public MainForm()
        {
            InitializeComponent();
            this.caption = this.Text;
            this.TopMost = true;

            pdfCreator = new PdfCreator(this);


            captureHelper = new CaptureHelper(this);
            captureHelper.CaptureStateChanged += new EventHandler(captureHelper_CaptureStateChanged);
            captureHelper.ReaderStateChanged += new EventHandler(captureHelper_ReaderStateChanged);

            tsbSettings.Click += new EventHandler(tsbSettings_Click);

            tsbCapture.Click += delegate(object sender, EventArgs e){Tool_CaptureScreen();};
            tsbSetRect.Click += delegate(object sender, EventArgs e){Tool_SetSelectedRect();};

            tsbCreatePDF.Click += new EventHandler(tsbCreatePDF_Click);

            tsbCompanyLink.Click += new EventHandler(tsbHelp_Click);

            LoadSettings();

            tsbStart.Click += delegate(object sender, EventArgs e) { Tool_Start(); };
            tsbPause.Click += delegate(object sender, EventArgs e){Tool_Pause();};
            tsbStop.Click += delegate(object sender, EventArgs e){Tool_Stop();};

            //tsbPrevPage.Click += delegate(object sender, EventArgs e){cmder.PrevPage();};
            //tsbNextPage.Click += delegate(object sender, EventArgs e){cmder.NextPage();};

            tsbContCapture.Click += new EventHandler(tsbContCapture_Click);


            toolBar.Resize += new EventHandler(toolBar_Resize);
            toolBar_Resize(this, EventArgs.Empty);
        }

        void tsbCreatePDF_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Multiselect = true;
            ofd.Title = "选择作为页面的图片(多幅)";
            ofd.Filter = "图片文件(*.bmp;*.png;*.jpg;*.gif)|*.bmp;*.png;*.jpg;*.gif|所有文件(*.*)|*.*";
            if (ofd.ShowDialog(this.TopLevelControl) == DialogResult.OK)
            {
                pdfCreator.CreatePDF(docTitle, ofd.FileNames);
            }
        }

        void captureHelper_CaptureStateChanged(object sender, EventArgs e)
        {
            UpdateButtons();
            if (captureHelper.CaptureState == CaptureState.Stop)
            {
                DialogResult result = MessageBox.Show(this.TopLevelControl,
                    "捕捉完毕，是否将捕捉到的这组图片生成为 PDF 文档？",
                    "提示",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {//生成 PDF 文档
                    pdfCreator.CreatePDF(docTitle, captureHelper.ImageFiles);
                }
                else
                {//打开保存的目录
                    if (Directory.Exists(captureHelper.SavedPath))
                    {
                        try
                        {
                            System.Diagnostics.Process.Start(captureHelper.SavedPath);
                        }
                        catch (Exception)
                        { }
                    }
                }
            }
        }
        void tsbContCapture_Click(object sender, EventArgs e)
        {//捕捉
            SettingsForm form = new SettingsForm(captureHelper, pdfCreator);
            form.ShowDialog(this.TopLevelControl);
        }
        void toolBar_Resize(object sender, EventArgs e)
        {
            if (toolBar.Width > 0 && toolBar.Height > 0)
            {
                this.ClientSize = toolBar.Size;
            }
        }

        void captureHelper_ReaderStateChanged(object sender, EventArgs e)
        {
            if (captureHelper.ReaderState == ReaderState.RunningAndOpenDocument
                || captureHelper.ReaderState == ReaderState.RunningButNoDocument)
            {//运行中
                toolBar.SuspendLayout();
                tsbStart.Visible = true;
                tsbPause.Visible = true;
                tsbStop.Visible = true;
                separator2.Visible = true;
                //tsbPrevPage.Visible = true;
                //tsbNextPage.Visible = true;
                //separator3.Visible = true;
                toolBar.ResumeLayout(true);

                UpdateButtons();
            }
            else
            {//不在运行，或未知
                if (captureHelper.CaptureState == CaptureState.Stop)
                {//自动捕捉未启动
                    UpdateButtons();
                }
                else
                {
                    //停止自动捕捉
                    captureHelper.Stop();
                    MessageBox.Show(this.TopLevelControl, "Apabi Reader 已经最小化或已经退出，无法继续捕捉。", "提示");
                    Tool_Stop();
                }

                toolBar.SuspendLayout();
                tsbStart.Visible = false;
                tsbPause.Visible = false;
                tsbStop.Visible = false;
                separator2.Visible = false;
                //tsbPrevPage.Visible = false;
                //tsbNextPage.Visible = false;
                //separator3.Visible = false;
                toolBar.ResumeLayout(true);
            }
            string docTitle = captureHelper.DocumentTitle;
            if(docTitle == null || docTitle.Trim() == "")
                this.Text = this.caption;
            else
                this.Text = this.caption+" ["+ docTitle + "]";
        }

        void tsbHelp_Click(object sender, EventArgs e)
        {//访问网站
            try
            {
                System.Diagnostics.Process.Start("http://chuangen.name/");
            }
            catch
            {
                //无法打开网站。
            }
        }

        void LoadSettings()
        {
            Point location = settings.MainFormLocation;
            if (location == Point.Empty || !Screen.PrimaryScreen.Bounds.Contains(new Rectangle(location, this.Size)))
            {//如果屏幕无法显示设置的位置，则
                this.StartPosition = FormStartPosition.CenterParent;
            }
            else
            {
                this.StartPosition = FormStartPosition.Manual;
                this.Location = settings.MainFormLocation;
            }

            captureHelper.CaptureInterval = settings.CaptureInterval;
            captureHelper.FocusBorderColor = settings.FocusBorderColor;

            if (settings.SelectedCmder != null || settings.SelectedCmder != "")
            {
                captureHelper.CmderName = settings.SelectedCmder;
            }

        }
        void SaveSettings()
        {
            settings.MainFormLocation = this.Location;
            settings.SelectedCmder =captureHelper.CmderName;

            settings.Save();
        }

        void tsbSettings_Click(object sender, EventArgs e)
        {
            Tool_Options();
        }
        /// <summary>
        /// 引发 <see cref="E:System.Windows.Forms.Form.Load"></see> 事件。
        /// </summary>
        /// <param name="e">包含事件数据的 <see cref="T:System.EventArgs"></see>。</param>
        protected override void OnLoad(EventArgs e)
        {
            RegHotkeys();
            base.OnLoad(e);

            captureHelper_ReaderStateChanged(this, EventArgs.Empty);
            UpdateButtons();
        }
        /// <summary>
        /// 引发 <see cref="E:System.Windows.Forms.Form.FormClosing"></see> 事件。
        /// </summary>
        /// <param name="e">包含事件数据的 <see cref="T:System.Windows.Forms.FormClosingEventArgs"></see>。</param>
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            SaveSettings();

            base.OnFormClosing(e);
        }

        /// <summary>
        /// WNDs the proc.
        /// </summary>
        /// <param name="m">The m.</param>
        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            // 快捷键消息处理
            Hotkey.ProcessHotKey(m);
        }

        void RegHotkeys()
        {
            HotkeyValue hotkeyCapture = settings.CaptureHotkey;
            HotkeyValue hotkeySetRect = settings.SetRectHotkey;
            HotkeyValue hotkeyStart = settings.HotkeyStart;
            HotkeyValue hotkeyPause = settings.HotkeyPause;
            HotkeyValue hotkeyStop = settings.HotkeyStop;
            //new Hotkey.HotKeyCallBackHanlder(Tool_Zoom)
            this.Regist(hotkeyCapture, Tool_CaptureScreen);
            this.Regist(hotkeySetRect, Tool_SetSelectedRect);
            this.Regist(hotkeyStart, Tool_Start);
            this.Regist(hotkeyPause, Tool_Pause);
            this.Regist(hotkeyStop, Tool_Stop);

            //menuZoom.ShortcutKeys = keys[0].Modifiers | keys[0].KeyCode;
            //menuDraw.ShortcutKeys = keys[1].Modifiers | keys[1].KeyCode;
            tsbCapture.Text = string.Format("捕捉屏幕({0})", hotkeyCapture.ToString());
            tsbSetRect.Text = string.Format("设置区域({0})", hotkeySetRect.ToString());
            tsbStart.Text = string.Format("开始连续捕捉({0})", hotkeyStart.ToString());
            tsbPause.Text = string.Format("暂停连续捕捉({0})", hotkeyPause.ToString());
            tsbStop.Text = string.Format("停止连续捕捉({0})", hotkeyStop.ToString());
        }
        void UnRegHotkeys()
        {
            Hotkey.UnRegist(this.Handle, Tool_CaptureScreen);
            Hotkey.UnRegist(this.Handle, Tool_SetSelectedRect);
            Hotkey.UnRegist(this.Handle, Tool_Start);
            Hotkey.UnRegist(this.Handle, Tool_Pause);
            Hotkey.UnRegist(this.Handle, Tool_Stop);
        }
        /// <summary>
        /// 引发 <see cref="E:System.Windows.Forms.Form.Closing"></see> 事件。
        /// </summary>
        /// <param name="e">包含事件数据的 <see cref="T:System.ComponentModel.CancelEventArgs"></see>。</param>
        protected override void OnClosing(CancelEventArgs e)
        {
            UnRegHotkeys();
            base.OnClosing(e);
        }

        bool Regist(HotkeyValue value, HotKeyCallBackHanlder callback)
        {
            HotkeyModifiers m = HotkeyModifiers.None;
            if ((value.Modifiers & Keys.Control) != 0)
                m |= HotkeyModifiers.MOD_CONTROL;
            if ((value.Modifiers & Keys.Shift) != 0)
                m |= HotkeyModifiers.MOD_SHIFT;
            if ((value.Modifiers & Keys.Alt) != 0)
                m |= HotkeyModifiers.MOD_ALT;

            bool result = false;
            try
            {
                Hotkey.Regist(this.Handle, m, value.KeyCode, callback);
                result = true;
            }
            catch (Exception)
            {
                result = false;
            }

            return result;
        }
        /// <summary>
        /// 工具|选项 命令。
        /// </summary>
        void Tool_Options()
        {
            OptionsForm form = new OptionsForm();
            form.StartPosition = FormStartPosition.CenterScreen;
            form.ShowInTaskbar = false;

            //先禁用热键
            UnRegHotkeys();
            DialogResult result = form.ShowDialog(this.TopLevelControl);
            if (result == DialogResult.OK)//设置新的热键
            {
                //重设捕捉频率。
                captureHelper.CaptureInterval = settings.CaptureInterval;
                captureHelper.FocusBorderColor = settings.FocusBorderColor;
            }

            //再注册新键
            RegHotkeys();
        }
    }
}